package com.example.util;

import com.example.context.BaseContext;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            sendError(response, "No valid token");
            return false;
        }
        token = token.substring(7);
        try {
            Claims claims = JwtUtils.parseToken(token);
            Long userId = claims.get("userId", Long.class);
            // 将用户ID存入ThreadLocal
            BaseContext.setCurrentId(userId);
            return true;
        } catch (JwtException e) {
            sendError(response, "Token is invalid or expired");
            return false;
        }
    }
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler,
                                Exception ex) throws Exception {
        // 请求结束后清除ThreadLocal数据，防止内存泄漏
        BaseContext.removeCurrentId();
    }

    private void sendError(HttpServletResponse response, String msg) throws IOException {
        response.setStatus(401);
        response.setContentType("application/json");
        response.getWriter().write("{\"code\":401, \"msg\":\"" + msg + "\"}");
    }
}
